package com.choosefine.it.basedata.controller;

import com.choosefine.it.basedata.model.UnitType;
import com.choosefine.it.basedata.service.UnitTypeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiResponse;
import io.swagger.annotations.ApiResponses;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import com.choosefine.it.base.BaseController;
import com.choosefine.it.base.dto.PageDTO;
import com.choosefine.it.basedata.model.CompanyInfo;
import com.choosefine.it.basedata.model.dto.FindCompanyCondition;
import com.choosefine.it.basedata.model.vo.AffiliatedUnitVO;
import com.choosefine.it.basedata.model.vo.CompanyInfoFindVO;
import com.choosefine.it.basedata.model.vo.CompanyNameFindVO;
import com.choosefine.it.basedata.service.CompanyInfoService;
import com.choosefine.it.common.def.CommonConstant;
import com.choosefine.it.common.def.ResultCode;
import com.choosefine.it.common.utils.DateUtils;
import com.choosefine.it.common.utils.PagedResult;
import com.choosefine.it.common.utils.StringUtils;
import com.github.pagehelper.Page;

/**
 * 公司详情相关控制层
 * 
 * @author guwenwei 2016/11/16
 */
@RestController
@RequestMapping("/basedata/companyinfo")
@Api(value = "公司详情相关", description = "顾文伟")
public class CompanyInfoController extends BaseController {
	Logger logger = LoggerFactory.getLogger(CompanyInfoController.class);
	@Autowired
	CompanyInfoService companyinfoService;
	@Autowired
	UnitTypeService unitTypeService;

	/**
	 * 添加公司详情
	 * 
	 * @param companyinfo
	 * @param
	 * @return
	 * @throws Exception
	 */
	@ApiOperation(value = "存储公司详情", notes = "传入公司对象，存储公司详情数据。")
	@ResponseBody
	@ApiResponses({
			@ApiResponse(code = ResultCode.SUCCESS_CREATED, message = "添加成功返回结果"),
			@ApiResponse(code = ResultCode.FAILED, message = "请求参数错误") })
	@RequestMapping(method = RequestMethod.POST)
	public String save(@RequestBody CompanyInfo companyinfo) {
		String result = null;
		if (companyinfo != null) {
			companyinfo.setCtime(DateUtils.getNowTime());
			companyinfo.setIsValid(CommonConstant.VALID);
			Integer num = companyinfoService.insert(companyinfo);
			logger.info("savecompanyinfo================="
					+ companyinfo.toString());
			if (num > 0) {
				result = responseSuccess(num);
			} else {
				result = responseFail(ResultCode.MSG_ERROR);
			}
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}

	@ApiOperation(value = "修改公司详情", notes = "传入公司对象，更改公司详情数据。")
	@ResponseBody
	@ApiResponses({
			@ApiResponse(code = ResultCode.SUCCESS_CREATED, message = "添加成功返回结果"),
			@ApiResponse(code = ResultCode.FAILED, message = "请求参数错误") })
	@RequestMapping(method = RequestMethod.PUT)
	public String update(@RequestBody CompanyInfo companyinfo) {
		String result = null;
		if (companyinfo != null) {
			companyinfo.setUtime(DateUtils.getNowTime());
			Integer num = companyinfoService.update(companyinfo);
			if (num > 0) {
				result = responseSuccess(num);
			} else {
				result = responseFail(ResultCode.MSG_ERROR);
			}
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}

	@ApiOperation(value = "根据用户UserCode取公司详情", notes = "传入用户编号，通过用户编号获取公司详情数据")
	@ApiImplicitParam(name = "userCode", value = "用户UserCode", required = true, dataType = "String", paramType = "path")
	@RequestMapping(value = "/UserCode/{userCode}", method = RequestMethod.GET)
	public String getCompanyByUserCode(@PathVariable String userCode) {
		String result = null;
		if (userCode != null) {
			CompanyInfo companyinfo = companyinfoService.findByUserCode(userCode);
			result = responseSuccess(companyinfo);
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}

	@ApiOperation(value = "按条件查找公司类型租户")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "companyType", value = "公司类型", dataType = "String", required = false, paramType = "query"),
			@ApiImplicitParam(name = "userCode", value = "用户编号", dataType = "String", required = false, paramType = "query"),
			@ApiImplicitParam(name = "companyName", value = "公司名称", dataType = "String", required = false, paramType = "query"),
			@ApiImplicitParam(name = "companyLegal", value = "法定代表人", dataType = "String", required = false, paramType = "query"),
			@ApiImplicitParam(name = "userStatus", value = "账户启用状态", dataType = "Integer", required = false, paramType = "query"),
			@ApiImplicitParam(name = "pageNum", value = "起始页", dataType = "Integer", required = true, paramType = "query"),
			@ApiImplicitParam(name = "pageSize", value = "每页行", dataType = "Integer", required = true, paramType = "query"),
			@ApiImplicitParam(name = "orderBy", value = "排序", dataType = "String", required = true, paramType = "query")})
	@RequestMapping(value = "/selectCompanyInfoBy", method = RequestMethod.GET)
	public String selectUserMgtBy(String companyType, String userCode,
			String companyName, String companyLegal, Integer userStatus,
			Integer pageNum, Integer pageSize,String orderBy) {
		String result = null;
		PageDTO pageDTO = new PageDTO();
		pageDTO.setPageNum(pageNum);
		pageDTO.setPageSize(pageSize);
		pageDTO.setOrderBy(orderBy);
		Map<String, Object> map = new HashMap<>();
		if (companyType != null && !"".equals(companyType)) {
			map.put("companyType", companyType);
		}
		if (userCode != null && !"".equals(userCode)) {
			map.put("userCode", userCode);
		}
		if (companyName != null && !"".equals(companyName)) {
			map.put("companyName", companyName);
		}
		if (companyLegal != null && !"".equals(companyLegal)) {
			map.put("companyLegal", companyLegal);
		}
		if (userStatus != null && !"".equals(userStatus)) {
			map.put("userStatus", userStatus);
		}
		List<CompanyInfo> list = companyinfoService.selectCompanyInfoBy(map,
				pageDTO);
		if (list != null) {
			result = responseArraySuccess(PagedResult.toPageInfo(list));
		} else {
			result = responseFail();
		}
		return result;
	}

	@ApiOperation(value = "根据用户UserCode删除公司详情", notes = "传入用户编号，通过用户编号删除公司详情数据，批量操作字符串逗号分割")
	@ApiImplicitParam(name = "userCodes", value = "用户UserCode", required = true, dataType = "String", paramType = "path")
	@RequestMapping(value = "/userCodes/{userCodes}", method = RequestMethod.DELETE)
	public String deleteByUserCode(@PathVariable String userCodes) {
		String result = null;
		if (userCodes != null) {
			Integer num = companyinfoService.deleteByUserCode(userCodes);
			if (num.intValue() > 0) {
				result = responseSuccess(num);
			} else {
				result = responseFail(ResultCode.MSG_ERROR);
			}
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}

	/**
	 * @author chenjian
	 * @time 2016-12-12 下午2:14:52
	 */
	@ApiOperation(value = "根据条件查询公司信息", notes = "控制台-项目管理-项目基本资料",response=CompanyInfoFindVO.class)
	@RequestMapping(value = "/findCompanyByRole", method = RequestMethod.POST, produces = "application/json")
	public String findCompanyByRole(
			@RequestBody FindCompanyCondition findCompanyCondition) {
		String result = null;
		Map<String, Object> params = new HashMap<>();
		// 用户角色
		params.put("roleId", findCompanyCondition.getRoleId());
		// 租户编号或法人
		if (findCompanyCondition.getCodeOrLegal() != null
				&& !"".equals(findCompanyCondition.getCodeOrLegal().trim())) {
			params.put("codeOrLegal", findCompanyCondition.getCodeOrLegal().trim());
		}
		PageDTO pageDTO = new PageDTO();
		pageDTO.setPageNum(findCompanyCondition.getPageNum());
		pageDTO.setPageSize(findCompanyCondition.getPageSize());
		if (findCompanyCondition.getRoleId() != null) {
			Page<CompanyInfoFindVO> list = companyinfoService.findCompanyByRole(
					params, pageDTO);
			if (list.size() > 0) {
				result = responseArraySuccess(list.toPageInfo());
			} else {
				result = responseFail(ResultCode.FAILED,
						ResultCode.MSG_DATA_ISEMPTY);
			}
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}

	@ApiOperation(value = "根据id查询公司信息", notes = "")
	@RequestMapping(value = "/selectCompanyInfoById/{id}", method = RequestMethod.GET, produces = "application/json")
	public String selectCompanyInfoById(@PathVariable Integer id) {
		if (id != null) {
			CompanyInfo companyInfo = companyinfoService
					.selectCompanyInfoById(id);
			if (companyInfo != null) {
				return responseSuccess(companyInfo, ResultCode.SUCCESS,
						ResultCode.MSG_QUERY_SUCCESS);
			} else {
				return responseFail(ResultCode.FAILED,
						ResultCode.MSG_DATA_ISEMPTY);
			}
		}
		return responseFail(ResultCode.MSG_PARAMS_NULL);
	}

	@ApiOperation(value = "根据公司name查usercode")
	@RequestMapping(value = "/getUserCodeByName/{companyName}", method = RequestMethod.GET)
	public String getUserCodeByName(@PathVariable String companyName) {
		String result = null;
		if (companyName != null) {
			String userCode = companyinfoService
					.selectUseCodeByName(companyName);
			if (userCode != null) {
				result = responseSuccess(userCode);
			} else {
				result = responseFail(ResultCode.MSG_DATA_ISEMPTY);
			}
		} else {
			result = responseFail(ResultCode.MSG_DATA_ISEMPTY);
		}

		return result;

	}

	@ApiOperation(value = "查看企业类型")
    @RequestMapping(value = "getEnterpriseType",method = RequestMethod.GET)
	public  String getEnterpriseType(){
		List<UnitType> unitTypes=unitTypeService.selectAllUnitType();
		String result=responseSuccess(unitTypes);
		return result;
	}
	
	/**
	 * @Description：根据角色查询公司信息不分页（陈健）
	 * @Author：chenjian
	 * @Create Date：2017年2月20日
	 * @param：
	 * @return：
	 */
	@ApiOperation(value = "根据角色查询公司信息不分页（陈健）", notes = "控制台-项目管理-项目基本资料",response=CompanyNameFindVO.class)
	@RequestMapping(value = "/findCompanyByUserCode/{userCode}", method = RequestMethod.GET, produces = "application/json")
    @ApiImplicitParam(name="userCode",value="分包承包人租户编号",required = true, dataType = "String", paramType = "path")
	public String findCompanyByUserCode(@PathVariable String userCode) {
		String result = null;
		if (StringUtils.isNotBlank(userCode)) {
			Map<String,Object> map = new HashMap<>();
			map.put("userCode", userCode);
			Page<CompanyNameFindVO> list = companyinfoService.findCompanyByUserCode(userCode);
			if (list.size() > 0) {
				result = responseArraySuccess(list);
			} else {
				result = responseFail(ResultCode.FAILED,
						ResultCode.MSG_DATA_ISEMPTY);
			}
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}
	
	/**
	 * @Description：项目资金管理-根据分包承包人租户编号建筑公司信息（陈健）
	 * @Author：chenjian
	 * @Create Date：2017年2月22日
	 * @param：
	 * @return：
	 */
	@ApiOperation(value = "项目资金管理-根据分包承包人租户编号建筑公司信息（陈健）", notes = "控制台-项目管理-项目基本资料",response=CompanyNameFindVO.class)
	@RequestMapping(value = "/findCompanyByManagerUserCode/{managerUserCode}", method = RequestMethod.GET, produces = "application/json")
    @ApiImplicitParam(name="managerUserCode",value="项目承包人租户编号",required = true, dataType = "String", paramType = "path")
	public String findCompanyByManagerUserCode(@PathVariable String managerUserCode) {
		String result = null;
		if (StringUtils.isNotBlank(managerUserCode)) {
			Map<String,Object> map = new HashMap<>();
			map.put("managerUserCode", managerUserCode);
			Page<CompanyNameFindVO> list = companyinfoService.findCompanyByManagerUserCode(managerUserCode);
			if (list.size() > 0) {
				result = responseArraySuccess(list);
			} else {
				result = responseFail(ResultCode.FAILED,
						ResultCode.MSG_DATA_ISEMPTY);
			}
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}
	
	/**
	 * @Description：分包承包人挂靠分包单位 信息列表（陈健）
	 * @Author：chenjian
	 * @Create Date：2017年3月9日
	 * @param：
	 * @return：
	 */
	@ApiOperation(value = "分包承包人挂靠分包单位 信息列表（陈健）", notes = "控制台-用户管理-个人类型租户管理",response=AffiliatedUnitVO.class)
	@RequestMapping(value = "/affiliatedUnits/{userCode}/{pageNum}/{pageSize}", method = RequestMethod.GET, produces = "application/json")
	@ApiImplicitParams({
		@ApiImplicitParam(name="userCode",value="分包承包人租户编号",required = true, dataType = "String", paramType = "path"),
		@ApiImplicitParam(name="pageNum",value="起始页",required = true, dataType = "integer", paramType = "path"),
		@ApiImplicitParam(name="pageSize",value="页大小",required = true, dataType = "integer", paramType = "path")
	})
	public String affiliatedUnits(@PathVariable String userCode,@PathVariable Integer pageNum,@PathVariable Integer pageSize) {
		String result = null;
		if (StringUtils.isNotBlank(userCode)) {
			PageDTO pageDTO = new PageDTO();
			pageDTO.setPageNum(pageNum);
			pageDTO.setPageSize(pageSize);
			Page<AffiliatedUnitVO> list = companyinfoService.findAffiliatedUnits(pageDTO,userCode);
			if (list.size() > 0) {
				result = responseArraySuccess(list.toPageInfo());
			} else {
				result = responseSuccess(null);
			}
		} else {
			result = responseFail(ResultCode.MSG_PARAMS_NULL);
		}
		return result;
	}

}
